package com.fqy.thread03.readwrite;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * User: fqy
 * Date: 2021/9/4
 * Time: 9:43
 * Describe: 读写操作
 */
public class MyCache {

    Map<String,String> map = new HashMap<>();

    final ReentrantReadWriteLock rtrwl = new ReentrantReadWriteLock();

    public void write(String key,String value){
        rtrwl.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName()+"准备写入");
            String result = map.put(key, value);
            System.out.println(Thread.currentThread().getName()+"完成写入"+result);
        }finally {
            rtrwl.writeLock().unlock();
        }
    }
    public void read(String key){
        rtrwl.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName()+"准备读入");
            String result = map.get(key);
            System.out.println(Thread.currentThread().getName()+"完成读入"+result);
        }finally {
            rtrwl.readLock().unlock();
        }
    }

/*    Lock lock = new ReentrantLock();

    public void write(String key,String value){
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName()+"准备写入");
            String result = map.put(key, value);
            System.out.println(Thread.currentThread().getName()+"完成写入"+result);
        }finally {
            lock.unlock();
        }
    }

    public void read(String key){
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName()+"准备读入");
            String result = map.get(key);
            System.out.println(Thread.currentThread().getName()+"完成读入"+result);
        }finally {
            lock.unlock();
        }
    }*/


}
